package cn.t222.service;

import cn.t222.mapper.SysRoleMapper;
import cn.t222.mapper.SysUserMapper;
import cn.t222.pojo.SysRole;
import cn.t222.pojo.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@CacheConfig(cacheNames = {"user-service"})
public class UserService implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @CachePut(key = "targetClass + ':get:' + #user.id")
    public SysUser add(SysUser user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        sysUserMapper.add(user);
        return user;
    }
    @CacheEvict(allEntries = true)
    public int del(Integer id) {
        return sysUserMapper.del(id);
    }
    @CachePut(key = "targetClass + ':get:' + #user.id")
    public SysUser update(SysUser user) {
        sysUserMapper.update(user);
        return user;
    }
    @Cacheable(key = "targetClass + ':get:' + #id")
    public SysUser get(Integer id) {
        return sysUserMapper.get(id);
    }

    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }

    @Override
    @Cacheable(key = "targetClass + ':'+methodName+':' + #username")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.loadUserByUsername(username);
        if(sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<SysRole> roles = sysRoleMapper.getByUserId(sysUser.getId());
        sysUser.setSysRoles(roles);
        return sysUser;
    }
//    @Cacheable(key = "targetClass + ':' + methodName + ':' + #username")
    public List<SysUser> getAllByUsername(String username) {
        List<SysUser> list = sysUserMapper.getAllByUsername(username);
        return list;
    }
}
